package com.xjj.util.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xjj.entity.Manager;
import com.xjj.entity.Parent;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : 王泰元
 * @description: TODO
 * @date : 2022/8/9 14:15
 */
public class JwtUtil {
    // 签名密钥
    static final String secret = "a309ty87ui64 0r79wjgl7ul6 a30gkty87p94";
    // 过期时间，单位：分钟
    static final Integer expire = 30;


    private static Map<String, Object> createToken() {
        DateTime now = DateTime.now();
        DateTime expireTime = now.offsetNew(DateField.MINUTE, expire);

        Map<String, Object> payload = new HashMap<>();

        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);

        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, expireTime);

        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);

        return payload;
    }

    public static String createToken(Integer userId) {

        Map<String, Object> payload = createToken();
        //载荷
        payload.put("id", userId);

        return JWTUtil.createToken(payload, secret.getBytes());
    }

    public static String createToken(String objectJSON, String name) {
        Map<String, Object> payload = createToken();

        //载荷
        payload.put(name, objectJSON);

        return JWTUtil.createToken(payload, secret.getBytes());
    }


    //    校验JWT的方法
    public static boolean verifyJWT(String token) {
        boolean verify;
        try {
            JWT jwt = JWTUtil.parseToken(token);
            JWT key = jwt.setKey(secret.getBytes());
            verify = key.verify();
        } catch (Exception e) {
            e.printStackTrace();
            verify = false;
        }
        return verify;
    }


    //    获取JWT中用户自定义的数据
    public static Object getInfo(String token, String name) {
        JWT jwt = JWTUtil.parseToken(token);
        return jwt.getPayload(name);
    }

    //  获取 jwt 中存储的 Manager 对象（后台管理系统登录主体）
    public static Manager getManager(String token) throws JsonProcessingException {
        String managerJSON = (String) getInfo(token, "manager");
        return new ObjectMapper().readValue(managerJSON, Manager.class);
    }

    //  获取 jwt 中存储的 Parent 对象（小程序登录主体）
    public static Parent getParent(String token) throws JsonProcessingException {
        String managerJSON = (String) getInfo(token, "parent");
        return new ObjectMapper().readValue(managerJSON, Parent.class);
    }
}
